package com.shenghuai.bclient.stores.util

import androidx.core.graphics.Insets
import androidx.fragment.app.Fragment
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import com.shenghuai.bclient.stores.common.OnDestroyLifeObserver
import com.shenghuai.bclient.stores.common.OnResumeLifeObserver

/**
 * 扩展fragment的功能
 */
fun Fragment.contextValid(): Boolean {
    return activity != null && activity?.isFinishing == false
}

fun Fragment.addOnResumeObserver(blocking: Function0<Unit>) {
    if (lifecycle.currentState.isAtLeast(Lifecycle.State.RESUMED)) {
        blocking()
    } else {
        lifecycle.addObserver(OnResumeLifeObserver {
            blocking()
        })
    }
}

fun Fragment.addOnStartObserver(blocking: Function0<Unit>, removeObserver: Boolean = true) {
    if (lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED))
        blocking()
    lifecycle.addObserver(object : DefaultLifecycleObserver {
        override fun onStart(owner: LifecycleOwner) {
            super.onStart(owner)
            blocking()
            if (removeObserver) {
                lifecycle.removeObserver(this)
            }
        }
    })

}

fun Fragment.addOnDestroyObserver(blocking: Function0<Unit>) {
    if (lifecycle.currentState.isAtLeast(Lifecycle.State.DESTROYED)) {
        blocking()
    } else {
        lifecycle.addObserver(OnDestroyLifeObserver {
            blocking()
        })
    }
}